/**
 * @fileOverview
 * @author rekey
 * Created by rekey on 25/5/14.
 */
var path = require('path');
var fs = require('fs');
var toPromise = require('./toPromise.js');
var qiniu = require('./qiniu.js');

function upload(filename, type) {
  var basename = path.basename(filename);
  if (path.extname(filename) === '') {
    basename = basename + '.' + type;
  }
  return toPromise(qiniu.upload)(filename, basename);
}

module.exports = function (filename, type) {
  if (path.extname(filename) === '') {
    return new Promise(function (resolve, reject) {
      var rename = toPromise(fs.rename);
      var newFilename = filename + '.' + type;
      var promise = rename(filename, newFilename);
      promise.then(function () {
        resolve(upload(newFilename, type));
      }, function (err) {
        reject(err);
      });
    });
  } else {
    return filename;
  }
};